<template>
  <div class="table-box">
    <div class="header">
      <button class="nav-button" @click="goToPreviousStep">上一步</button>
      <div class="steps-container">
        <div v-for="(step, index) in steps" :key="index" :class="['step-box', { active: index === 2 }]">
          {{ step }}
        </div>
      </div>
      <button class="nav-button" @click="goToNextStep">下一步</button>
    </div>
    <ProTable ref="proTable" title="物料列表" :columns="columns" :data="productList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <SelectFilter :data="filterData" @change="changeFilter" :default-values="filterResult" />
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="goToModal(scope.row)">内部工序碳排放清单</el-button>
      </template>
    </ProTable>
    <ImportExcel ref="dialogRef" />
    <!-- 添加核算层次选择对话框 -->
    <el-dialog v-model="levelDialogVisible" title="选择核算层次" width="500px" append-to-body>
      <div class="data-source-options">
        <div
          v-for="level in accountingLevels"
          :key="level.value"
          class="data-source-option"
          @click="handleLevelSelect(level.value)"
        >
          <div class="source-icon">
            <el-icon :size="24">
              <component :is="level.icon" />
            </el-icon>
          </div>
          <div class="source-info">
            <h4>{{ level.label }}</h4>
            <p>{{ level.description }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, onMounted } from "vue";
import { ProcessCarbonEmission, Product } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { EditPen, Histogram, Box } from "@element-plus/icons-vue";
import SelectFilter from "@/components/SelectFilter/index.vue";
import { useRouter, useRoute } from "vue-router";
import { flowChartList, processCarbonEmissions } from "@/assets/mock/mockData";

const router = useRouter();
const route = useRoute();

// 从路由参数中获取 projectId
const projectId = route.params.projectId;

const filterResult = ref({ state: "2" });
const changeFilter = (val: typeof filterResult.value) => {
  filterResult.value = val;
  if (val.state === "1") {
    router.push({
      path: `/lca/inventory/materialIndex/${projectId}`
    });
  }
};

// 所有产品数据
const projectList = [
  {
    projectId: "1",
    id: "1",
    productId: "P001",
    productName: "高压开关柜",
    description: "用于电力系统中高压设备的控制和保护。",
    createTime: "2023-12-01 10:00:00"
  },
  {
    projectId: "2",
    id: "8",
    productId: "P008",
    productName: "变压器",
    description: "变压器是电力系统中重要的电气设备，用于电压的升降和电流的传输。",
    createTime: "2023-12-01 10:00:00"
  },
  {
    projectId: "3",
    id: "19",
    productId: "P019",
    productName: "高压开关柜_新",
    description: "用于电力系统中高压设备的控制和保护。",
    createTime: "2023-12-01 10:00:00"
  }
];

// 当前显示的产品数据
const productList = ref<typeof projectList>([]);

// 初始化数据
onMounted(() => {
  const currentProduct = projectList.find(item => item.projectId === projectId);
  productList.value = currentProduct ? [currentProduct] : [];
});

const filterData = [
  {
    title: "核算层次",
    key: "state",
    options: [
      {
        label: "物料层",
        value: "1",
        icon: "Guide"
      },
      {
        label: "产品层",
        value: "2",
        icon: "Van"
      }
    ]
  }
];

const steps = ["产品碳排放源分析", "外购零部件碳排放值收集", "产品生产装配碳排放值收集"];

// 上一步
const goToPreviousStep = () => {
  router.push(`/lca/inventory/structureTree/${projectId}`);
};

// 核算层次选择相关
const levelDialogVisible = ref(false);
const accountingLevels = [
  {
    label: "产品层",
    value: "product",
    description: "在产品层面进行碳足迹核算",
    icon: Box
  },
  {
    label: "物料层",
    value: "material",
    description: "在物料层面进行碳足迹核算",
    icon: Histogram
  }
];

// 修改下一步按钮的处理函数
const goToNextStep = () => {
  levelDialogVisible.value = true;
};

const handleLevelSelect = (level: string) => {
  levelDialogVisible.value = false;

  if (level === "product") {
    // 先从 localStorage 中查找数据
    const key = `flowChart_${projectId}_2`;
    const savedFlowChart = localStorage.getItem(key);
    console.log("从 localStorage 中查找数据:", key);

    let flowChartData;
    if (savedFlowChart) {
      flowChartData = JSON.parse(savedFlowChart);
      console.log("从 localStorage 中找到数据:", flowChartData);
    } else {
      // 如果 localStorage 中没有，从 mockData 中查找
      flowChartData = flowChartList.value.find(item => item.projectId === projectId && item.objectType === "2");
      console.log("从 mockData 中查找数据:", flowChartData);
    }

    if (flowChartData) {
      // 将数据存储到 processCarbonEmissions
      const carbonEmissionData: ProcessCarbonEmission.ProcessCarbonEmission = {
        projectId: projectId as string,
        objectId: flowChartData.objectId as string,
        nodes: flowChartData.nodes as ProcessCarbonEmission.FlowChartNode[]
      };
      console.log("carbonEmissionData", carbonEmissionData);

      // 查找是否已存在相同的数据
      const existingIndex = processCarbonEmissions.value.findIndex(
        item => item.projectId === projectId && item.objectId === flowChartData.objectId
      );

      if (existingIndex !== -1) {
        processCarbonEmissions.value[existingIndex] = carbonEmissionData;
        console.log("更新已存在的碳排放数据:", carbonEmissionData);
      } else {
        processCarbonEmissions.value.push(carbonEmissionData);
        console.log("添加新的碳排放数据:", carbonEmissionData);
      }

      // 将数据存入 localStorage
      const storageKey = `processCarbonEmission_${projectId}`;
      localStorage.setItem(storageKey, JSON.stringify(carbonEmissionData));
      console.log("将碳排放数据存入 localStorage:", storageKey);
    }

    // 跳转到 impact/index 页面
    router.push(`/lca/impact/index/${projectId}`);
  } else if (level === "material") {
    // 从 localStorage 获取 purposeScopeData
    const storedData = localStorage.getItem(`purposeScopeData_${projectId}`);
    const purposeScopeData = storedData ? JSON.parse(storedData) : null;
    console.log("purposeScopeData", purposeScopeData);
    const objectId = purposeScopeData?.id;

    if (!objectId) {
      console.error("未找到对应的 objectId");
      return;
    }

    // 从 flowChartList 中查找所有相关的流程图数据
    const materialFlowCharts = flowChartList.value.filter(item => item.projectId === projectId && item.objectType === "1");
    const assemblyFlowChart = flowChartList.value.find(item => item.projectId === projectId && item.objectType === "0");

    console.log("物料层流程图数据:", materialFlowCharts);
    console.log("装配流程图数据:", assemblyFlowChart);

    // 合并所有节点
    let allNodes: ProcessCarbonEmission.FlowChartNode[] = [];

    // 添加物料工艺节点
    materialFlowCharts.forEach(flowChart => {
      if (flowChart.nodes) {
        allNodes = allNodes.concat(flowChart.nodes as ProcessCarbonEmission.FlowChartNode[]);
      }
    });

    // 添加装配工艺节点
    if (assemblyFlowChart?.nodes) {
      allNodes = allNodes.concat(assemblyFlowChart.nodes as ProcessCarbonEmission.FlowChartNode[]);
    }

    // 创建碳排放数据
    const carbonEmissionData: ProcessCarbonEmission.ProcessCarbonEmission = {
      projectId: projectId as string,
      objectId: objectId,
      nodes: allNodes
    };

    console.log("合并后的碳排放数据:", carbonEmissionData);

    // 查找是否已存在相同的数据
    const existingIndex = processCarbonEmissions.value.findIndex(
      item => item.projectId === projectId && item.objectId === objectId
    );

    if (existingIndex !== -1) {
      processCarbonEmissions.value[existingIndex] = carbonEmissionData;
      console.log("更新已存在的碳排放数据");
    } else {
      processCarbonEmissions.value.push(carbonEmissionData);
      console.log("添加新的碳排放数据");
    }

    // 将数据存入 localStorage
    const storageKey = `processCarbonEmission_${projectId}`;
    localStorage.setItem(storageKey, JSON.stringify(carbonEmissionData));
    console.log("将碳排放数据存入 localStorage:", storageKey);

    // 跳转到 impact/index 页面
    router.push(`/lca/impact/index/${projectId}`);
  }
};

// 监听过滤器的变化

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

const goToModal = (row: any) => {
  let typeId = 2; // 默认值为2（产品建模）
  router.push({
    path: `/lca/inventory/processFlow/${projectId}/${typeId}/${row.id}`
  });
};
// 表格配置项
const columns: ColumnProps<Product.ResProduct>[] = [
  {
    prop: "productId",
    label: "产品编号"
  },
  {
    prop: "productName",
    label: "产品名称"
  },
  {
    prop: "description",
    label: "产品描述"
  },
  { prop: "operation", label: "操作", fixed: "right", width: 400 } // 操作列
];
</script>
<style>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  margin-bottom: 20px;
  background-color: #ffffff;
  border-bottom: 1px solid #dddddd;
  border-radius: 8px;
}
.nav-button {
  padding: 10px 20px;
  font-size: 16px;
  color: white;
  cursor: pointer;
  background-color: #009688;
  border: none;
  border-radius: 5px;
  transition: background-color 0.3s;
}
.nav-button:hover {
  background-color: #007d6a;
}
.steps-container {
  display: flex;
  justify-content: space-between;
  width: 80%;
  padding: 0 20px;
}
.step-box {
  position: relative;
  flex: 1;
  padding: 15px 10px;
  margin: 0 10px;
  color: #777777;
  text-align: center;
  cursor: pointer;
  background-color: #f9f9f9;
  border: 1px solid #dcdcdc;
  border-radius: 5px;
  transition: all 0.3s;
}
.step-box.active {
  font-weight: bold;
  color: #009688;
  background-color: #e6f5f3;
  border-color: #009688;
}
.step-box::after {
  position: absolute;
  top: 50%;
  right: -20px;
  font-size: 20px;
  color: #009688;
  content: "→";
  transform: translateY(-50%);
}
.step-box:last-child::after {
  visibility: hidden;
}

/* 数据来源选择对话框样式 */
.data-source-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 20px;
}
.data-source-option {
  display: flex;
  align-items: center;
  padding: 16px;
  cursor: pointer;
  background: #ffffff;
  border: 1px solid #e6f5f3;
  border-radius: 8px;
  transition: all 0.3s;
}
.data-source-option:hover {
  border-color: #009688;
  box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}
.source-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  margin-right: 16px;
  color: #009688;
  background: #e6f5f3;
  border-radius: 8px;
}
.source-info {
  flex: 1;
}
.source-info h4 {
  margin: 0 0 4px;
  font-size: 16px;
  color: #303133;
}
.source-info p {
  margin: 0;
  font-size: 13px;
  color: #909399;
}
</style>
